<script setup lang="ts">
import VDialog from "@/components/VDialog/VDialog.vue";
import { computed, reactive, ref, watch, onMounted } from "vue";
import {
  AddInspectionCommand,
  InspectionPageResponse,
  UpdateInspectionCommand,
  addInspectionApi,
  updateInspectionApi,
  UserInfo,
  ApiResponse,
  assertApiResponse
} from "@/api/airport/inspection/inspection";
import { useUserStoreHook } from "@/store/modules/user";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { getUsersByDeptIdApi } from "./utils/hook";
import { getDeptTree, DeptTreeDTO } from "@/api/system/dept";






interface Props {
  type: "add" | "update";
  modelValue: boolean;
  row?: InspectionPageResponse;
}

const props = defineProps<Props>();
const emits = defineEmits<{
  (e: "update:modelValue", v: boolean): void;
  (e: "success"): void;
}>();

const visible = computed({
  get: () => props.modelValue,
  set(v) {
    emits("update:modelValue", v);
  }
});

const formData = reactive<AddInspectionCommand | UpdateInspectionCommand>({
  inspectionName: "",
  inspectionSource: "",
  startTime: "",
  endTime: "",
  inspectionContent: "",
  inspectionDeptId: undefined,
  createBy: "",
  createTime: "",
  updateBy: "",
  updateTime: "",
  remark: "",
  status: "",
  planDate: "",
  inspectionCode: "",
  checkCount: 0,
  checkOkCount: 0,
  type: "",
  inspectionPeriod: "",
  inspectionLevel: "",
  approver: 0,
  deptId: undefined,
  checkUseridList: "",
  checkUserId: undefined,
  creatorId: 0,
  updaterId: 0,
  deleted: false
});

const statusList = {
  ...useUserStoreHook().dictionaryMap["inspection.status"],
  '0': '计划待提交',
  '1': '计划待审批',
  '2': '计划已驳回',
  '3': '检查待开始',
  '4': '正在检查',
  '5': '已完成'
};
const inspectionTypeOptions = [
  { label: "法定自查", value: "FDZC" },
  { label: "专项检查", value: "ZXJC" },
  { label: "安全质量检查", value: "AQZL" }
];
const inspectionSourceOptions = [
  { label: "年度检查", value: "1" },
  { label: "临时检查", value: "2" }
];
const inspectionPeriodOptions = [
  { label: "年度", value: "1" },
  { label: "月度", value: "2" },
  { label: "无", value: "3" }
];
const inspectionLevelOptions = [
  { label: "公司", value: "1" },
  { label: "部门", value: "2" },
  { label: "科室", value: "3" }
];
const deptTree = ref<DeptTreeDTO[]>([]);
const userList = ref<Array<{ id: number; name: string }>>([]);

const rules: FormRules = {
  inspectionName: [
    {
      required: true,
      message: "检查名称不能为空"
    }
  ],
  type: [
    {
      required: true,
      message: "检查类型不能为空"
    }
  ],
  inspectionSource: [
    {
      required: true,
      message: "检查来源不能为空"
    }
  ],
  inspectionPeriod: [
    {
      required: true,
      message: "检查周期不能为空"
    }
  ],
  planDate: [
    {
      required: true,
      message: "计划时间不能为空"
    }
  ],
  inspectionDeptId: [
    {
      required: true,
      message: "检查对象不能为空"
    }
  ],
  inspectionLevel: [
    {
      required: true,
      message: "检查级别不能为空"
    }
  ],
  inspectionContent: [
    {
      required: true,
      message: "检查内容不能为空"
    }
  ],
  deptId: [
    {
      required: true,
      message: "检查部门不能为空"
    }
  ],
  checkUserId: [
    {
      required: true,
      message: "小组组长不能为空"
    }
  ],
};

const formRef = ref<FormInstance>();

// 处理检查小组选择
const selectedCheckUsers = ref<number[]>([]);

function handleOpened() {
  // 每次打开弹窗时清空 selectedCheckUsers
  selectedCheckUsers.value = [];
  // 同时清空 formData 中的 checkUseridList 和 checkUserId
  formData.checkUseridList = "";
  formData.checkUserId = undefined;

  if (props.row) {
    Object.assign(formData, props.row);

  } else {
    formRef.value?.resetFields();
  }
}

const loading = ref(false);

async function handleConfirm() {
  if (!formRef.value) return;
  try {

    // 执行表单验证
    await formRef.value.validate();
    // 在提交时更新 checkUseridList 和 checkUserId
    const userStore = useUserStoreHook(); // 获取用户状态管理实例
    formData.createBy = userStore.currentUserInfo?.username;
    debugger


    formData.checkUseridList = "";
    formData.checkUseridList = selectedCheckUsers.value.map(Number).join(",");
    formData.checkUserId = Number(formData.checkUserId);

    loading.value = true;
    if (props.type === "add") {
      await addInspectionApi(formData);
    } else if (props.type === "update") {
      await updateInspectionApi(formData as UpdateInspectionCommand);
    }
    ElMessage.info("提交成功");
    visible.value = false;
    emits("success");
  } catch (error) {
    console.error(error);
    ElMessage.error("请填写完整必填项");
  } finally {
    loading.value = false;
  }
}
// 根据部门 ID 查询用户列表
watch(
  () => formData.deptId,
  async (deptId) => {
    if (deptId) {
      const response = await getUsersByDeptIdApi(deptId);
      if (assertApiResponse(response) && response.code === 0) {
        // 提取需要的 userId 和 username 字段
        userList.value = response.data.map((user) => ({
          id: user.userId,
          name: user.username
        }));
      } else {
        userList.value = [];
      }
    } else {
      userList.value = [];
    }
  }
);

// 处理小组组长选择
// 移除原来的 watch 监听逻辑

// 转换部门树数据格式
const convertDeptTree = (nodes: DeptTreeDTO[]) => {
  return nodes.map((node) => ({
    value: node.id,
    label: node.label,
    children: node.children ? convertDeptTree(node.children) : undefined
  }));
};

// 获取部门树数据
const fetchDeptTree = async () => {
  try {
    const { data } = await getDeptTree();
    if (data) {
      if (Array.isArray(data)) {
        deptTree.value = convertDeptTree(data);
      } else {
        deptTree.value = convertDeptTree([data]);
      }
    }
  } catch (error) {
    console.error("获取部门树数据失败:", error);
  }
};

// 组件挂载时获取部门树数据
onMounted(() => {
  fetchDeptTree();
});
</script>

<template>
  <v-dialog
    show-full-screen
    :fixed-body-height="false"
    use-body-scrolling
    :title="props.type === 'add' ? '新增检查计划' : '更新检查计划'"
    v-model="visible"
    :loading="loading"
    @confirm="handleConfirm"
    @cancel="visible = false"
    @opened="handleOpened"
  >
    <!-- 绑定 rules 和 ref 到 el-form -->
    <el-form :model="formData" label-width="120px" :rules="rules" ref="formRef">
      <el-row :gutter="20">
        <el-col :span="23">
          <el-form-item prop="inspectionName" label="检查名称" required inline-message>
            <el-input v-model="formData.inspectionName" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="14">
          <el-form-item prop="type" label="检查类型" required>
            <el-radio-group v-model="formData.type">
              <el-radio
                v-for="item in inspectionTypeOptions"
                :key="item.value"
                :label="item.value"
              >
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">

        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="inspectionSource" label="检查来源" required>
            <el-radio-group v-model="formData.inspectionSource">
              <el-radio
                v-for="item in inspectionSourceOptions"
                :key="item.value"
                :label="item.value"
              >
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="inspectionPeriod" label="检查周期" required>
            <el-radio-group v-model="formData.inspectionPeriod">
              <el-radio
                v-for="item in inspectionPeriodOptions"
                :key="item.value"
                :label="item.value"
              >
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item prop="planDate" label="计划时间" required>
        <el-date-picker
          v-model="formData.planDate"
          type="date"
          value-format="YYYY-MM-DD"
        placeholder="选择计划时间"
        />
      </el-form-item>
      <el-form-item prop="inspectionDeptId" label="检查对象" required>
        <el-cascader
          v-model="formData.inspectionDeptId"
          :options="deptTree"
          :props="{
            value: 'value',
            label: 'label',
            emitPath: false,
            checkStrictly: true
          }"
          clearable
          placeholder="请选择检查对象"
        />
      </el-form-item>
      <el-form-item prop="inspectionLevel" label="检查级别" required>
        <el-radio-group v-model="formData.inspectionLevel">
          <el-radio
            v-for="item in inspectionLevelOptions"
            :key="item.value"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="23">
          <el-form-item prop="inspectionContent" label="检查内容" required>
            <el-input type="textarea" rows="4" v-model="formData.inspectionContent" />
          </el-form-item>
        </el-col>
      </el-row>


      <el-form-item prop="deptId" label="检查部门" required>
        <el-cascader
          v-model="formData.deptId"
          :options="deptTree"
          :props="{
            value: 'value',
            label: 'label',
            emitPath: false,
            checkStrictly: true
          }"
          clearable
          placeholder="请选择检查部门"
        />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="checkUseridList" label="检查小组">
            <el-checkbox-group v-model="selectedCheckUsers">
              <el-checkbox
                v-for="user in userList"
                :key="user.id"
                :label="user.id"
              >
                {{ user.name }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item prop="checkUserId" label="小组组长" required>
            <!-- 将下拉框改为单选框 -->
            <el-radio-group v-model="formData.checkUserId">
              <el-radio
                v-for="user in userList"
                :key="user.id"
                :label="user.id"
              >
                {{ user.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="23">
          <el-form-item prop="remark" label="备注">
            <el-input type="textarea" rows="4" v-model="formData.remark" />
          </el-form-item>
          <!-- 添加空的 el-form-item 来留出空隙 -->
          <el-form-item></el-form-item>
        </el-col>
      </el-row>




    </el-form>
  </v-dialog>
</template>
